package com.huashi.dealer.modular.controller.api.balance;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.UserBalanceApply;
import com.huashi.dealer.commonEntity.UserBalanceLog;
import cn.dev33.satoken.stp.StpUtil;
import com.huashi.dealer.core.page.PageFactory;
import com.huashi.dealer.core.pojo.CommonResult;
import com.huashi.dealer.core.util.SaTokenUtil;
import com.huashi.dealer.modular.business.balance.service.BalanceService;
import com.huashi.dealer.modular.business.balance.param.BalanceRequestParam;
import com.huashi.dealer.modular.business.balance.param.BalanceResponseParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * API打款单控制器
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
@Tag(name = "API打款单控制器")
@RestController("apiBalanceController")
@RequestMapping("/api/balance")
@Validated
public class BalanceController {

    @Resource
    private BalanceService balanceService;

    /**
     * 申请打款单
     */
    @PostMapping("/apply")
    @Operation(summary = "申请打款单")
    public CommonResult<String> applyBalance(
                                            @RequestParam(required = false) String money,
                                            @RequestParam(value = "images", required = false) String images) {
        try {
            balanceService.applyBalance(money, images);
            return CommonResult.ok("申请成功");
        } catch (Exception e) {
            return CommonResult.error("申请打款单失败：" + e.getMessage());
        }
    }

    /**
     * 余额日志列表
     */
    @GetMapping("/log/lists")
    @Operation(summary = "余额日志列表")
    public CommonResult<Page<UserBalanceLog>> getBalanceLogList(@RequestParam(defaultValue = "30") Integer time) {
        try {
            // 创建分页对象
            Page<UserBalanceLog> page = PageFactory.defaultPage();
            Page<UserBalanceLog> responseParam= balanceService.getBalanceLogList(page,time);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取余额日志列表失败：" + e.getMessage());
        }
    }

    /**
     * 余额详情
     */
    @GetMapping("/detail")
    @Operation(summary = "余额详情")
    public CommonResult<BalanceResponseParam> getBalanceDetail(@RequestParam(required = false) String token) {
        try {
            BalanceResponseParam responseParam = balanceService.getBalanceDetail(token);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取余额详情失败：" + e.getMessage());
        }
    }

    /**
     * 提现申请
     */
    @PostMapping("/withdraw")
    @Operation(summary = "提现申请")
    public CommonResult<String> withdrawBalance(@RequestBody BalanceRequestParam requestParam) {
        try {
            balanceService.withdrawBalance(requestParam);
            return CommonResult.ok("提现申请成功");
        } catch (Exception e) {
            return CommonResult.error("提现申请失败：" + e.getMessage());
        }
    }

    /**
     * 打款单列表
     */
    @GetMapping("/apply/lists")
    @Operation(summary = "打款单列表")
    public CommonResult<BalanceResponseParam> getBalanceApplyList(@RequestParam(required = false) String token,
                                                                  @RequestParam(required = false) Integer page,
                                                                  @RequestParam(required = false) Integer listRows) {
        try {
            BalanceResponseParam responseParam = balanceService.getBalanceApplyList(token, page, listRows);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取打款单列表失败：" + e.getMessage());
        }
    }

    /**
     * 打款单详情
     */
    @GetMapping("/apply/detail/{applyId}")
    @Operation(summary = "打款单详情")
    public CommonResult<BalanceResponseParam> getBalanceApplyDetail(@PathVariable Long applyId,
                                                                    @RequestParam(required = false) String token) {
        try {
            BalanceResponseParam responseParam = balanceService.getBalanceApplyDetail(applyId, token);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取打款单详情失败：" + e.getMessage());
        }
    }

    /**
     * 取消打款单
     */
    @PostMapping("/apply/cancel/{applyId}")
    @Operation(summary = "取消打款单")
    public CommonResult<String> cancelBalanceApply(@PathVariable Long applyId,
                                                   @RequestParam(required = false) String token) {
        try {
            balanceService.cancelBalanceApply(applyId, token);
            return CommonResult.ok("取消成功");
        } catch (Exception e) {
            return CommonResult.error("取消打款单失败：" + e.getMessage());
        }
    }

    /**
     * 余额充值
     */
    @PostMapping("/recharge")
    @Operation(summary = "余额充值")
    public CommonResult<BalanceResponseParam> rechargeBalance(@RequestBody BalanceRequestParam requestParam) {
        try {
            BalanceResponseParam responseParam = balanceService.rechargeBalance(requestParam);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("余额充值失败：" + e.getMessage());
        }
    }

    /**
     * 提交充值申请
     */
    @PostMapping("/balanceapply")
    @Operation(summary = "提交充值申请")
    public CommonResult<UserBalanceApply> submitBalanceApply(@RequestParam String money,
                                                           @RequestParam String images) {
        try {
            // 获取当前登录用户ID
            Long userId = SaTokenUtil.getLoginId();

            UserBalanceApply balanceApply = balanceService.submitBalanceApply(userId, new BigDecimal(money), images);
            return CommonResult.data(balanceApply);
        } catch (Exception e) {
            return CommonResult.error("提交充值申请失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户充值申请列表
     */
    @GetMapping("/balanceapply/lists")
    @Operation(summary = "获取用户充值申请列表")
    public CommonResult<Page<UserBalanceApply>> getUserBalanceApplyList(@RequestParam(defaultValue = "1") Integer page,
                                                                       @RequestParam(defaultValue = "15") Integer size) {
        try {
            // 获取当前登录用户ID
            Long userId = SaTokenUtil.getLoginId();

            Page<UserBalanceApply> pageParam = new Page<>(page, size);
            Page<UserBalanceApply> balanceApplyList = balanceService.getUserBalanceApplyList(userId, pageParam);
            return CommonResult.data(balanceApplyList);
        } catch (Exception e) {
            return CommonResult.error("获取充值申请列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取充值申请详情
     */
    @GetMapping("/balanceapply/detail/{applyId}")
    @Operation(summary = "获取充值申请详情")
    public CommonResult<UserBalanceApply> getBalanceApplyDetail(@PathVariable Long applyId) {
        try {
            // 获取当前登录用户ID
            Long userId = SaTokenUtil.getLoginId();

            UserBalanceApply balanceApply = balanceService.getBalanceApplyDetailById(applyId, userId);
            return CommonResult.data(balanceApply);
        } catch (Exception e) {
            return CommonResult.error("获取充值申请详情失败：" + e.getMessage());
        }
    }

    /**
     * 审核充值申请（管理员接口）
     */
    @PostMapping("/balanceapply/audit/{applyId}")
    @Operation(summary = "审核充值申请")
    public CommonResult<String> auditBalanceApply(@PathVariable Long applyId,
                                                @RequestParam Integer balanceStatus,
                                                @RequestParam(required = false) String rejectReason) {
        try {
            // 获取当前登录用户ID（审核员）
            Long salesmanStoreUserId = SaTokenUtil.getLoginId();

            boolean result = balanceService.auditBalanceApply(applyId, balanceStatus, rejectReason, salesmanStoreUserId);
            if (result) {
                return CommonResult.ok("审核成功");
            } else {
                return CommonResult.error("审核失败");
            }
        } catch (Exception e) {
            return CommonResult.error("审核充值申请失败：" + e.getMessage());
        }
    }
} 